package com.adopapa.nezhacloud.ddd.controller;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.adopapa.nezhacloud.common.Tools;

public abstract class BaseController {

	protected Logger logger = LoggerFactory.getLogger(getClass());

//	protected Mono<ServerResponse> redirect(String targetUrl) {
//
//		return ServerResponse.temporaryRedirect(URI.create(targetUrl)).build();
//	}

	// -Djava.net.preferIPv4Stack=true
//	protected String getRemoteIp(ServerHttpRequest request) {
//		return request.getRemoteAddress().getAddress().getHostAddress();
//
//	}

	@SuppressWarnings("unchecked")
	protected <T> T getMapValue(Map<String, Object> paramMap, String key, Class<T> klazz) {
		// FIXME
		try {
			if (paramMap == null || paramMap.isEmpty() || Tools.empty(paramMap.get(key))) {
				return null;
			}
			if (klazz == String.class) {
				return (T) paramMap.get(key);
			}
			if (klazz == Integer.class || klazz == int.class) {
				return (T) (Integer) Integer.parseInt(String.valueOf(paramMap.get(key)));
			}
			if (klazz == Long.class || klazz == long.class) {
				return (T) (Long) Long.parseLong(String.valueOf(paramMap.get(key)));
			}
			if (klazz == Double.class || klazz == double.class) {
				return (T) (Double) Double.parseDouble(String.valueOf(paramMap.get(key)));
			}
			if (klazz == BigDecimal.class) {
				if (paramMap.get(key) instanceof Integer) {
					return (T) (BigDecimal) BigDecimal.valueOf((Integer) paramMap.get(key) * 1.0D);
				} else if (paramMap.get(key) instanceof Double) {
					return (T) (BigDecimal) BigDecimal.valueOf((Double) paramMap.get(key) * 1.0D);
				} else { // string
					return (T) (BigDecimal) BigDecimal.valueOf(Double.parseDouble(String.valueOf(paramMap.get(key))));
				}
			}
			if (klazz == Boolean.class || klazz == boolean.class) {
				return (T) (Boolean) Boolean.valueOf(String.valueOf(paramMap.get(key)));
			}
			if (klazz == List.class) {
				return (T) paramMap.get(key);
			}
			return (T) paramMap.get(key);
		} catch (Exception e) {
			logger.error(ExceptionUtils.getStackTrace(e));
			return null;
		}

	}
	

}
